//
//  HEIMMessageCell.m
//  HealthElderly
//
//  Created by 吴欧 on 2020/11/27.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEIMMessageCell.h"
#import "HEIMKit.h"

@interface HEIMMessageCell ()

@property (nonatomic, assign) HEIMMessageOwnerType messageOwner;
@property (nonatomic, assign) HEIMUserModelType messageChatType;

//FIXME:retain cycle
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation HEIMMessageCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = KHexColor(@"f6f6f6");

        [self getMessageOwner];
        [self getMessageChatType];
        [self makeComponents];
        [self makeGesture];
    }
    return self;
}

- (void)makeGesture {
    UITapGestureRecognizer *headTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userHeadClick)];
    [_userHeadView addGestureRecognizer: headTap];
    
    UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressAvatar:)];
    [recognizer setMinimumPressDuration:0.5f];
    [_userHeadView addGestureRecognizer:recognizer];
    
    UILongPressGestureRecognizer *cntRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(contentHandleLongPress:)];
    [recognizer setMinimumPressDuration:0.4f];
    [self.bubbleView addGestureRecognizer:cntRecognizer];
}

- (void)makeComponents {
    
    // 头像
    _userHeadView = [UIImageView new];
    _userHeadView.contentMode = UIViewContentModeScaleAspectFill;
    _userHeadView.userInteractionEnabled = YES;
    [self.contentView addSubview:_userHeadView];
    
    _userHeadView.layer.cornerRadius = 25;
    _userHeadView.layer.masksToBounds = YES;
    
    // 气泡
    UIView *bubbleView = [UIView new];
    bubbleView.backgroundColor = KWhiteColor;
    [self.contentView addSubview:bubbleView];
    _bubbleView = bubbleView;
    _bubbleView.layer.cornerRadius = 10;

//    bubbleView.layer.shadowColor = [UIColor colorWithRed:13/255.0 green:98/255.0 blue:218/255.0 alpha:0.08].CGColor;
//    bubbleView.layer.shadowOffset = CGSizeMake(0,5);
//    bubbleView.layer.shadowRadius = 6;
//    bubbleView.layer.shadowOpacity = 1;
//    bubbleView.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:bubbleView.bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)].CGPath;//参数依次为大小，设置四个角圆角状态，圆角曲度  设置阴影路径可避免离屏渲染


    
    // 菊花
    _traningActivityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0,0,20,20)];
    [self.contentView addSubview:_traningActivityIndicator];
    
    [self setupLayout];
//    [_traningActivityIndicator mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.equalTo(bubbleView);
////        make.left.equalTo(bubbleView.mas_right).mas_offset(10);
//        make.width.height.offset(20);
//    }];
//
//    [_userHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
//       make.top.equalTo(self.contentView).mas_offset(10);
//       make.left.equalTo(self.contentView).mas_offset(15);
////        make.centerX.equalTo(self.contentView).offset( KScreenWidth / 2.0 - 25 - 15 );
//       make.width.height.mas_offset(50);
//    }];
//
//    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.contentView).mas_offset(10);
//        make.left.equalTo(_userHeadView.mas_right).mas_offset(10);
//    }];
//
//    [bubbleView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(_nameLabel.mas_bottom).mas_offset(5);
////        make.left.equalTo(_userHeadView.mas_right).mas_offset(15);
//
////        make.right.equalTo(self.contentView).mas_offset( -(15 + 50 + 5));
////        make.centerX.equalTo(self.contentView).offset( KScreenWidth / 2.0 - 100 / 2.0 - 50 - 15 - 10);
//        make.bottom.equalTo(self.contentView).mas_offset(-15);
//    }];
//
//    self.userHeadView.hidden = YES;
//    self.bubbleView.hidden = YES;
}

/// 是不是自己的消息
- (void)getMessageOwner {
    if ([self.reuseIdentifier containsString:HECellIdentifierOwnerSelf]) {
        self.messageOwner = HEIMMessageOwnerTypeSelf;
    }else if ([self.reuseIdentifier containsString:HECellIdentifierOwnerOther]) {
        self.messageOwner = HEIMMessageOwnerTypeOther;
    } else if ([self.reuseIdentifier containsString:HECellIdentifierSystem]) {
        self.messageOwner = HEIMMessageOwnerTypeSystem;
    }else {
        self.messageOwner = HEIMMessageOwnerTypeUnknown;
    }
}

- (void)getMessageChatType {
    if ([self.reuseIdentifier containsString:HECellIdentifierGroup]) {
        self.messageChatType = HEIMUserModelTypeTeamIM;
    }else {
        self.messageChatType = HEIMUserModelTypeIM;
    }
}

- (void)setupLayout {
    if (self.messageOwner == HEIMMessageOwnerTypeSystem || self.messageOwner == HEIMMessageOwnerTypeUnknown) {
        return;
    }
    
    if (self.messageOwner == HEIMMessageOwnerTypeSelf) {
        [_traningActivityIndicator mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bubbleView.mas_centerY);
            make.right.equalTo(self.bubbleView.mas_left).mas_offset(-10);
            make.width.height.offset(20);
        }];
        
        [_userHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.top.equalTo(self.contentView.mas_top).mas_offset(10);
           make.right.equalTo(self.contentView.mas_right).mas_offset(-15);
           make.width.height.mas_offset(50);
        }];
         
//        [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.contentView).mas_offset(10);
//            make.left.equalTo(_userHeadView.mas_right).mas_offset(10);
//        }];

        [self.bubbleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView.mas_top).mas_offset(15);
            make.right.equalTo(_userHeadView.mas_left).mas_offset(-10);
            
            CGFloat width = [UIApplication sharedApplication].keyWindow.frame.size.width;
            CGFloat height = [UIApplication sharedApplication].keyWindow.frame.size.height;
            CGFloat widthLimit = MIN(width, height)/5 * 3;
            
            make.width.lessThanOrEqualTo(@(widthLimit)).priorityHigh();
            make.bottom.equalTo(self.contentView.mas_bottom).mas_offset(-15).priorityLow();
        }];
    }else {
        [_traningActivityIndicator mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.bubbleView);
            make.right.equalTo(self.bubbleView.mas_left).mas_offset(10);
            make.width.height.offset(20);
        }];
        
        [_userHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.top.equalTo(self.contentView).mas_offset(10);
           make.left.equalTo(self.contentView).mas_offset(15);
           make.width.height.mas_offset(50);
        }];
        
        if (self.messageChatType == HEIMUserModelTypeTeamIM) {
            
            _nameLabel = [UILabel new];
            _nameLabel.text = @"-";
            _nameLabel.font = DYFont(15);
            _nameLabel.textColor = CNavDargGrayColor;
            [self.contentView addSubview:_nameLabel];
            
            [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.contentView).mas_offset(10);
                make.left.equalTo(_userHeadView.mas_right).mas_offset(10);
                make.right.equalTo(self.contentView).mas_offset(-50);
            }];

            [self.bubbleView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_nameLabel.mas_bottom).mas_offset(5);
                make.left.equalTo(_userHeadView.mas_right).mas_offset(10);
                
                CGFloat width = [UIApplication sharedApplication].keyWindow.frame.size.width;
                CGFloat height = [UIApplication sharedApplication].keyWindow.frame.size.height;
                CGFloat widthLimit = MIN(width, height)/5 * 3;
                make.width.lessThanOrEqualTo(@(widthLimit)).priorityHigh();
                make.bottom.equalTo(self.contentView).mas_offset(-15).priorityLow();
            }];
        }else {
            [self.bubbleView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.contentView).mas_offset(15);
                make.left.equalTo(_userHeadView.mas_right).mas_offset(10);
                
                CGFloat width = [UIApplication sharedApplication].keyWindow.frame.size.width;
                CGFloat height = [UIApplication sharedApplication].keyWindow.frame.size.height;
                CGFloat widthLimit = MIN(width, height)/5 * 3;
                
                make.width.lessThanOrEqualTo(@(widthLimit)).priorityHigh();
                make.bottom.equalTo(self.contentView).mas_offset(-15).priorityLow();
            }];
        }
    }
    
    [self.traningActivityIndicator mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.bubbleView.mas_left).offset(-10);
    }];
}

- (void)refreshData:(HEIMMessageModel *)data {

    _model = data;
    HEIMKitInfo *userInfo = [[HEIMKit sharedKit] infoByUser:data.message.from];
    [_userHeadView sd_setImageWithURL: userInfo.avatUrl placeholderImage: userInfo.avatarImage];
    _nameLabel.text = userInfo.showName;
    self.bubbleView.backgroundColor = data.warpColor;
    
    if (data.deliveryState == HEIMMessageDeliveryStateDeliveried) {
        [_traningActivityIndicator stopAnimating];
    }else {
        [_traningActivityIndicator startAnimating];
    }
  
//    [self updateLayoutSubViews];
//    [self layoutActivityIndicator];
//    [self updateUserNameLayout];
}

#pragma mark - 事件
- (void)userHeadClick {
    if ([_delegate respondsToSelector:@selector(onTapAvatar:)]) {
        [_delegate onTapAvatar: self.model.message];
    }
}

- (void)handleLongPressAvatar:(UIGestureRecognizer *)gestrue {
    //直接return掉，不在开始的状态里面添加任何操作，则长按手势就会被少调用一次了
    if (gestrue.state != UIGestureRecognizerStateBegan) {
       return;
    }
    if ([_delegate respondsToSelector:@selector(onLongPressAvatar:)]) {
        [_delegate onLongPressAvatar: self.model.message];
    }
}

- (void)contentHandleLongPress:(UILongPressGestureRecognizer *)longPressGes
{
    if (longPressGes.state == UIGestureRecognizerStateBegan) {

        if (!(self.model.message.type == HEIMMessageTypeText) &&
            !(self.model.message.type == HEIMMessageTypeAT)) {
            return;
        }
        
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        [self becomeFirstResponder];

        UIMenuItem *copyItems = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyHandler)];
        UIMenuController *menuController = [UIMenuController sharedMenuController];
        menuController.menuItems = @[copyItems];
        [menuController setArrowDirection:UIMenuControllerArrowDown];
        UITableView *tableView = self.tableView;
        CGRect targetRect = [self convertRect:self.bubbleView.frame toView:tableView];
        [menuController setTargetRect:targetRect inView:tableView];
        [menuController setMenuVisible:YES animated:YES];
    }
}

- (void)copyHandler {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString: self.model.message.text];
}

// 用于UIMenuController显示，缺一不可
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    if (action ==@selector(copyHandler)){
        return YES;
    }
    return NO;//隐藏系统默认的菜单项
}

- (UITableView *)tableView {
    if (!_tableView) {
        // 寻找Cell所属的tableView
        UIView *tableView = self.superview;
        while (![tableView isKindOfClass:[UITableView class]] && tableView) {
            tableView = tableView.superview;
        }
        _tableView = (UITableView *)tableView;
    }
    return _tableView;
}

#pragma mark -
//- (void)layoutSubviews
//{
//    [super layoutSubviews];
//    [self updateLayoutSubViews];
//    [self layoutActivityIndicator];
//}

/// 更新用户姓名布局
- (void)updateUserNameLayout {
    
    if (self.messageOwner == HEIMMessageOwnerTypeOther) {
        [self.nameLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_lessThanOrEqualTo(self.model.nameSize.width);
            make.height.mas_offset(self.model.nameSize.height);
        }];
    }
    
//    if (self.model.shouldShowNickName) {
//        [self.nameLabel mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.width.mas_lessThanOrEqualTo(self.model.nameSize.width);
//            make.height.mas_offset(self.model.nameSize.height);
//        }];
//    }else {
//         [self.nameLabel mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_offset(0);
//        }];
//    }
}

/// 更新用户头像和内容区域位置
- (void)updateLayoutSubViews {
    
    [self.userHeadView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(self.model.userHeadOriginX);
    }];
    
    [self.bubbleView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(self.model.warpOriginX);
    }];
    
    self.userHeadView.hidden = NO;
    self.bubbleView.hidden = NO;
        
//    dispatch_async(dispatch_get_main_queue(), ^{
//
//        CGRect userframe = self.userHeadView.frame;
//        CGRect bubbleViewframe = self.bubbleView.frame;
//
//        userframe.origin.x = self.model.userHeadOriginX;
//        bubbleViewframe.origin.x = self.model.warpOriginX;
//
//        self.userHeadView.frame = userframe;
//        self.bubbleView.frame = bubbleViewframe;
//
//        self.userHeadView.hidden = NO;
//        self.bubbleView.hidden = NO;
//
//    });
}

/// 更新菊花位置
- (void)layoutActivityIndicator {
    
    if (_traningActivityIndicator.isAnimating) {
        [self.traningActivityIndicator mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView).offset(self.model.activityIndOriginX);
        }];
    }
 
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if (_traningActivityIndicator.isAnimating) {
//            CGRect activiframe = self.traningActivityIndicator.frame;
//            activiframe.origin.x = self.model.activityIndOriginX;
//            _traningActivityIndicator.frame = activiframe;
//        }
//    });
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
